<?php

namespace App\Services;
use App\Exceptions\WorkException;
use App\Services\BaseServices;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use App\Util\Code;
use Illuminate\Support\Facades\Log;


class WxServices extends BaseServices{

    /**
     * 根据open_id获取用户是否存在
     * @param $openId
     * @return $data[ 'openid' ]|null|string
     */

    public function getByOpenId( $code )
    {

       $data = Http::get('https://api.weixin.qq.com/sns/jscode2session', [
            'appid'      => env("WX_APP_ID"),
            'secret'     => env("WX_SECRET"),
            'js_code'    => $code,
            'grant_type' => 'authorization_code',
        ]);


       $data = $data->json();

       Log::info('获取微信小程序openId:', $data);

       if ( isset( $data[ 'errcode' ] ) && $data[ 'errcode' ]!=0 ){

           Log::info('获取微信小程序openId异常:', $data);
           throw new WorkException( Code:: Wx_CLT_ILLEGAL);
       }

       return $data[ 'openid' ];
    }
}